package com.omesoft.hksnore.report;

import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.omesoft.hksnore.R;
import com.omesoft.hksnore.util.dao.MendaleSleepIfcImpl;
import com.omesoft.hksnore.util.data.MyDateUtil;
import com.omesoft.hksnore.util.entity.Medix_Pub_Sync_SleepDetail;
import com.omesoft.hksnore.util.myactivity.MyActivity;
import com.omesoft.hksnore.util.omeview.NumberSeekBar;
import com.omesoft.hksnore.util.omeview.SeekBarDrawble;
import com.omesoft.hksnore.util.photo.SettingUtil;
import com.omesoft.hksnore.util.snore.SnoreMonitorHis;
import com.omesoft.hksnore.util.titlebar.MyTitlebarUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Omesoft on 2017/3/7.
 */

public class RePlayActivity extends MyActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {

    private boolean isFirstDraw = true;
    private boolean isFinish1 = true;


    /**
     * 画布
     */
    private SurfaceView mSV;
    private SurfaceHolder mHolder;
    private boolean isOver = false;
    private boolean isPuse = false;

    private String fileName = "";

    private int Snore_Duration = 0;
    private TextView mSnoreCount_tv, mSnoreTimeHour_tv, mSnoreTImeMin_tv, mSnoreStopCount_tv,
            mBreathing_tv, mMove_tv, mTurnMova_tv, mStartTime_tv, mEndTime,mSnoreTimeMorS_tv;
    private TextView mSpeed_tv, mSnoreReback_tv;
    private ImageButton mPuse_btn, mFastest_btn;
    private RelativeLayout mSnorePlay_rl;

    private NumberSeekBar mSeekbar;

    // private float data0, data01, data11, data1;
    private ArrayList<Float> showedList0 = new ArrayList<Float>();
    private ArrayList<Float> showedList01 = new ArrayList<Float>();
    private ArrayList<Float> showedList1 = new ArrayList<Float>();
    private ArrayList<Float> showedList11 = new ArrayList<Float>();

    private Canvas canvas = null;

    private SnoreMonitorHis snoreMonitorHis;
    private String SleepID = "";
    private SeekBarDrawble drawable;
    private String startTime, endTime = "";

    /**
     * 已经显示的数据波形 最多能够显示的单位格数量(横坐标 15px 为一个单位格)
     */
    private int maxNum = 0;

    private boolean isSetMaxNum = false;

    private MendaleSleepIfcImpl mifc;
    private List<Medix_Pub_Sync_SleepDetail> detailList;
    private MediaPlayer mediaPlayer;
    private MyCountDownTimer timer;
    private File recoderFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.snore_activity_recall);
        init();
        initView();
        initTitleBar();
        initHandler();
    }

    @Override
    protected void initTitleBar() {
        super.initTitleBar();
        MyTitlebarUtil.showTitleName(activity, R.string.repotr_replay);
        MyTitlebarUtil.showIbLeft(activity, R.mipmap.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        isFinish1 = true;
        isSetMaxNum = false;
        Intent intent = getIntent();

        if (intent != null) {
            SleepID = intent.getStringExtra("SleepID");
            fileName = SleepID + ".txt";
            mSnoreCount_tv.setText(intent.getStringExtra("SnoreCount"));
            mSnoreStopCount_tv.setText(intent.getStringExtra("SnoreSropCount"));
            mSnoreTimeHour_tv.setText(intent.getStringExtra("SnoreTimeHour"));
            mSnoreTImeMin_tv.setText(intent.getStringExtra("SnoreTimeMin"));
            mBreathing_tv.setText(intent.getStringExtra("BreathingRata"));
            mMove_tv.setText(intent.getStringExtra("ActCount"));
            mTurnMova_tv.setText(intent.getStringExtra("TurnCount"));
            mSnoreTimeMorS_tv.setText(intent.getStringExtra("SnoreTimeMorS"));
            startTime = intent.getStringExtra("startTime");
            endTime = intent.getStringExtra("endTime");
            if (fileName != null) {
                if (snoreMonitorHis == null) {
                    snoreMonitorHis = new SnoreMonitorHis(RePlayActivity.this, handler, fileName);
                    snoreMonitorHis.start();
                    mSpeed_tv.setText(snoreMonitorHis.getFastMultiple() + "x");
                    recoderFile = new File(SettingUtil.TEXT_RECORD_DIR + "/" + SleepID);
                    if (recoderFile.exists()) {
                        mSnorePlay_rl.setBackground(getResources().getDrawable(R.drawable.replay_speed_btn_bg));
                        mSnorePlay_rl.setEnabled(true);
                    } else {
                        mSnorePlay_rl.setBackground(getResources().getDrawable(R.mipmap.report_palyback_snore_press));
                        mSnorePlay_rl.setEnabled(false);
                    }
                }
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (snoreMonitorHis != null) {
            snoreMonitorHis.monitorStop();
            snoreMonitorHis = null;
        }
    }

    @Override
    protected void init() {
        super.init();
        SettingUtil.isMove = false;
        SettingUtil.isFastForward = false;


    }

    @Override
    protected void initView() {
        super.initView();
        mifc = new MendaleSleepIfcImpl(context);
        mediaPlayer = new MediaPlayer();
        mSnoreCount_tv = (TextView) findViewById(R.id.recall_sonre_count);
        mSnoreTimeHour_tv = (TextView) findViewById(R.id.recall_sonre_time_hour);
        mSnoreTImeMin_tv = (TextView) findViewById(R.id.recall_sonre_time_min);
        mSnoreStopCount_tv = (TextView) findViewById(R.id.recall_sonre_stop);
        mBreathing_tv = (TextView) findViewById(R.id.recall_sonre_breath);
        mMove_tv = (TextView) findViewById(R.id.recall_sonre_move);
        mTurnMova_tv = (TextView) findViewById(R.id.recall_sonre_turn_mova);
        mStartTime_tv = (TextView) findViewById(R.id.recall_start_time);
        mEndTime = (TextView) findViewById(R.id.recall_end_time);
        mSpeed_tv = (TextView) findViewById(R.id.recall_speed_text);//快进
        mSnorePlay_rl = (RelativeLayout) findViewById(R.id.recall_sonre_play_audio_rl);
        mPuse_btn = (ImageButton) findViewById(R.id.recall_sonre_pause_play);
        mFastest_btn = (ImageButton) findViewById(R.id.recall_sonre_fastest);
        mSnoreTimeMorS_tv = (TextView) findViewById(R.id.recall_snore_m_or_s);
        mPuse_btn.setOnClickListener(this);
        mFastest_btn.setOnClickListener(this);
        mSnorePlay_rl.setOnClickListener(this);

        mSnoreReback_tv = (TextView) findViewById(R.id.recall_sonre_play_audio_reback);//播放20秒鼾声倒数文字

        mSV = (SurfaceView) findViewById(R.id.replay_sv);
        mSV.setZOrderOnTop(true);// 设置画布 背景透明
        mSV.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        mHolder = mSV.getHolder();
        mSeekbar = (NumberSeekBar) findViewById(R.id.recall_seekbar);

        timer = new MyCountDownTimer(20000, 1000);
        mSeekbar.setMax(SettingUtil.MAXCOUNT2);
        mSeekbar.setOnSeekBarChangeListener(this);
        mHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder surfaceHolder) {
                if (isOver) {
                    drawDataLine(canvas, showedList1, showedList11, mSV,
                            mHolder, 1);
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                Log.e("mul", "销毁。。。。。。。。。。。");
                isFinish1 = false;
            }
        });

    }

    @Override
    protected void initHandler() {
        super.initHandler();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0:
                        showedList0 = ((ArrayList<Float>) msg.obj);
                        break;
                    case 1:
                        showedList01 = (ArrayList<Float>) msg.obj;
                        break;
                    case 2:
                        showedList01 = (ArrayList<Float>) msg.obj;
                        break;
                    case 9:
                        showedList1 = (ArrayList<Float>) msg.obj;
                        if (isFinish1) {
                            drawDataLine(canvas, showedList1, showedList11, mSV, mHolder, 1);
                        }
                        break;
                    case 10:
                        showedList1 = (ArrayList<Float>) msg.obj;
                        if (isFinish1) {
                            drawDataLine(canvas, showedList1, showedList11, mSV, mHolder, 1);
                        }
                        break;
                    case 11://打鼾次数
                        if (!msg.obj.toString().contains("n")) {
                            //  mSnoreCount_tv.setText(msg.obj.toString());
                        }
                        break;
                    case 12://打鼾时长

                        if (!msg.obj.toString().contains("n")) {
                            //   Snore_Duration = Math.round(Float.parseFloat(msg.obj.toString()));
                            // setSnoreTime(Snore_Duration);
                        }

                        break;
                    case 15:// 呼吸频率
                        if (isFinish1) {
                            //   mBreathing_tv.setText(msg.obj.toString());
                        }
                        break;
                    case 16:// 体动次数
                        if (isFinish1) {
                            // mMove_tv.setText(msg.obj.toString());
                        }
                        break;
                    case 17:// 翻身次数
                        if (isFinish1) {
                            //  mTurnMova_tv.setText(msg.obj.toString());
                        }
                        break;
                    case 20:// 数据时间
                        if (isFinish1) {
                            mStartTime_tv.setText(msg.obj.toString());
                        }
                        break;
                    case 21:// 总时间
                        if (isFinish1) {
                            mEndTime.setText(msg.obj.toString());
                        }

                        break;
                    case 14:// 进度条的当前进度
                        int progress = (Integer) msg.obj;
                        mSeekbar.setProgress(progress);
                        break;
                    case 23:// 止鼾次数
                        // mSnoreStopCount_tv.setText(msg.obj.toString());
                        break;
                    case 18:
                        showedList11 = (ArrayList<Float>) msg.obj;
                        if (isFinish1) {
                            drawDataLine(canvas, showedList1, showedList11, mSV,
                                    mHolder, 1);
                        }
                        break;

                }
            }
        };
    }

    private void drawDataLine(Canvas canvas, ArrayList<Float> pointList, ArrayList<Float> pointList2, SurfaceView mySurfaceView, SurfaceHolder mHolder, int type) {

        try {
            canvas = mHolder.lockCanvas();
            canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);

            if (canvas == null) {
                return;
            }
            int width = mySurfaceView.getWidth();
            int height = mySurfaceView.getHeight();

            Paint linePaint = new Paint();
            linePaint.setStyle(Paint.Style.STROKE);
            // 判断是否是第一次在屏幕上画波形
            if (isFirstDraw) {
                maxNum = (width - 5) / 5;
            }
            if (!isSetMaxNum) {
                isSetMaxNum = true;
                snoreMonitorHis.setMaxNum(maxNum);
            }
            int lStartX = 0;
            int lStartY = 0;
            int temp = 0;
            int temp1 = 0;
            // 画背景格子
            float boxsize = (float) (height * 0.04);
            if (type != -1 || type == -2) {
                boxsize = 15;
            }
            float boxsize2 = 25;
            for (int i = 0; i < height; i++) {
                linePaint.setStrokeWidth(1);
                linePaint.setColor(Color.GRAY);
                // canvas.drawLine(lStartX, lSta
                // rtY, width + 4, lStartY,
                // linePaint);
                lStartY += boxsize2;
                // canvas.drawLine(temp, 0, temp, height, linePaint);
                temp1 = temp;
                // 控制竖线条数(最大位置不能超过width/2)
                if (temp < width) {
                    temp += boxsize2;
                }
            }
            width = temp1;
            float showedBeginX = 0;
            float showedEndX = 0;
            float showedBeginY = 0;
            float showedEndY = 0;

            int boxtH = (int) (height / boxsize);// 总共份数
            float eachHeight = (float) (128 / boxtH);
            // 第一个图
            if (pointList != null && pointList.size() > 0) {
                // // 如果数据集合中有数据
                linePaint.setColor(getResources().getColor(R.color.text_color));
                // 设置画笔的线条粗细
                linePaint.setStrokeWidth(3);
                linePaint.setAntiAlias(true);
                showedBeginX = width - (5 * pointList.size() + 5);
                showedEndX = showedBeginX + 5;
                showedBeginY = height - (float) (pointList.get(0) / eachHeight)
                        * boxsize;
                for (int i = 0; i < pointList.size(); i++) {
                    showedEndY = pointList.get(i);
                    float yPoint = height - (float) (showedEndY / eachHeight)
                            * boxsize;
                    if (type == 0) {
                        canvas.drawLine(showedBeginX, showedBeginY, showedEndX, yPoint, linePaint);
                    } else {

                        canvas.drawLine(showedBeginX, showedBeginY - height / 4, showedEndX, yPoint - height / 4, linePaint);
                    }

                    showedBeginX = showedEndX;
                    showedEndX = showedBeginX + 5;
                    showedBeginY = yPoint;
                    if (pointList.size() != 1 && pointList.size() != (i + 1)) {
                        try {
                            showedEndY = pointList.get(i + 1);
                        } catch (Exception e) {
                            e.printStackTrace();
                            break;
                        }
                    }
                    if (!isFinish1) {
                        return;
                    }
                }
                // 如果能完全显示已经显示过的波形数据就就直接添加进显示过波形数据的集合中否则去掉第一个再添加进去
                if (pointList.size() > maxNum) {
                    pointList.remove(0);
                }

                int simpleHeight = height / 6;
                linePaint.setTextSize(28);
                linePaint.setColor(Color.CYAN);
//                mSnoreStopCount_tv
//                        .setText(" : "
//                                + (Math.round(pointList.get((pointList.size() - 1)) * 10) / 10.0));
            }
            isFirstDraw = false;

            mHolder.unlockCanvasAndPost(canvas);// 更新屏幕显示内容
        } catch (Exception e) {
            mHolder.unlockCanvasAndPost(canvas);// 更新屏幕显示内容
            e.printStackTrace();
            Log.e("muk", "绘图工具1初始化出问题>>>>>>>>>>>");
        } finally {

        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.recall_sonre_pause_play:
                if (isPuse) {
                    isPuse = false;
                    snoreMonitorHis.monitorPuse(isPuse);
                    mPuse_btn.setBackground(getResources().getDrawable(R.drawable.replay_pause_btn_bg));
                } else {

                    isPuse = true;
                    snoreMonitorHis.monitorPuse(isPuse);
                    mPuse_btn.setBackground(getResources().getDrawable(R.drawable.replay_play_btn_bg));
                }
                break;
            case R.id.recall_sonre_fastest:
                int mul = snoreMonitorHis.setFastMultiple();
                if (mul == 0) {
                    snoreMonitorHis.setQuick(true);
                    mSpeed_tv.setText("速算");
                } else {
                    snoreMonitorHis.setQuick(false);
                    mSpeed_tv.setText(mul + "x");

                }
                break;
            case R.id.recall_sonre_play_audio_rl:

                calcSnorePosition();

                break;
        }

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

        SettingUtil.isMove = true;
        SettingUtil.isFastForward = true;
    }

    /**
     * 打鼾时长计算
     */
    private void setSnoreTime(int time) {
        int hour = time / 60;
        int min = time % 60;
        if (time >= 0) {
            if (time < 60) {
                mSnoreTimeHour_tv.setText("00");
                mSnoreTImeMin_tv.setText("0" + time);
            } else {
                if (hour < 10) {
                    mSnoreTimeHour_tv.setText("0" + hour);
                    if (min >= 0 && min < 10) {
                        mSnoreTImeMin_tv.setText("0" + min);
                    } else {
                        mSnoreTImeMin_tv.setText(min + "");
                    }
                } else {
                    mSnoreTimeHour_tv.setText(hour + "");
                    if (min >= 0 && min < 10) {
                        mSnoreTImeMin_tv.setText("0" + min);
                    } else {
                        mSnoreTImeMin_tv.setText(min + "");
                    }
                }
            }
        }
    }


    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        int currentProgress = seekBar.getProgress();
        moveProgress(currentProgress);
    }


    /**
     * 调整回放进度
     */
    private void moveProgress(int currentProgress) {
        // 清空画图
        SettingUtil.isMove = false;
        snoreMonitorHis.toDataPos(currentProgress);
        showedList0.clear();
        showedList01.clear();
        showedList1.clear();
        showedList11.clear();
        drawDataLine(canvas, showedList1, showedList11, mSV, mHolder, 1);
        // 传进度过去，返回新的值

    }

    /**
     * 计算鼾声所在位置
     */

    int index = 0;

    private void calcSnorePosition() {
        if (recoderFile.exists()) {
            File[] arraylist = recoderFile.listFiles();

            if (arraylist.length > 0) {
                try {
                    mediaPlayer.reset();
                    String filename = arraylist[index].toString();

                    mediaPlayer.setDataSource(filename);
                    mediaPlayer.prepare();
                    mediaPlayer.start();//播放音频

                    long start = MyDateUtil.stringTOlongDate2(startTime);
                    long end = MyDateUtil.stringTOlongDate2(endTime);
                    String s = filename.substring(filename.length() - 21, filename.length() - 4);
                    float snoretime = MyDateUtil.stringTOlongDate3(s) * 1.0F;
                    float snoreInPos = (snoretime - start) / (end - start) * 100;
                    if (arraylist.length >= 2) {
                        if (index == 0) {
                            index += 1;
                        } else {
                            index = 0;
                        }
                    }
                    SettingUtil.isMove = true;
                    SettingUtil.isFastForward = true;
                    moveProgress((int) snoreInPos);
                    mSeekbar.setProgress((int) snoreInPos);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            timer.start();
        }
    }

    class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub

        }

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
//            sendMsg(ReErrorCode.ERROR_VERIFY_BACKWARD, millisUntilFinished / 1000);
            mSnorePlay_rl.setEnabled(false);
            mSnorePlay_rl.setBackground(getResources().getDrawable(R.mipmap.report_palyback_snore_press));
            mSnoreReback_tv.setText((millisUntilFinished / 1000) + "");

        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub
            mSnorePlay_rl.setBackground(getResources().getDrawable(R.drawable.replay_speed_btn_bg));
            mSnoreReback_tv.setText(20 + "");
            mediaPlayer.stop();
            mSnorePlay_rl.setEnabled(true);

        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
    }
}
